import java.util.ArrayList;
import java.util.List;
import javax.faces.application.FacesMessage;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
import javax.faces.convert.FacesConverter;

@FacesConverter(value="playerConverter" ,forClass=Player.class)
public class PlayerConverter implements Converter {

	public static List<Player> playerDB;

	static {
		playerDB = new ArrayList<Player>();

		playerDB.add(new Player("756556757567", 10, "messi.jpg", "CF"));
		playerDB.add(new Player("345654889023", 9, "bojan.jpg", "CF"));
		playerDB.add(new Player("345554643923", 8, "iniesta.jpg", "CM"));
		playerDB.add(new Player("644554643i87", 7, "villa.jpg", "CF"));
		playerDB.add(new Player("234554643923", 6, "xavi.jpg", "CM"));
		playerDB.add(new Player("435678764322", 5, "puyol.jpg", "CB"));
		playerDB.add(new Player("109876654345", 20, "afellay.jpg", "AMC"));
		playerDB.add(new Player("456845124390", 22, "abidal.jpg", "LB"));
		playerDB.add(new Player("198476743859", 2, "alves.jpg", "RB"));
		playerDB.add(new Player("345678876334", 3, "pique.jpg", "CB"));
		playerDB.add(new Player("823344675454", 15, "keita.jpg", "DM"));
		playerDB.add(new Player("554654346745", 21, "adriano.jpg", "LB"));
		playerDB.add(new Player("336784894370", 1, "valdes.jpg", "GK"));
	}

	public Object getAsObject(FacesContext facesContext, UIComponent component,
			String submittedValue) {
		if (submittedValue.trim().equals("")) {
			return null;
		} else {
			try {
				int number = Integer.parseInt(submittedValue);

				for (Player p : playerDB) {
					if (p.getNumber() == number) {
						return p;
					}
				}

			} catch (NumberFormatException exception) {
				throw new ConverterException(new FacesMessage(
						FacesMessage.SEVERITY_ERROR, "Conversion Error",
						"Not a valid player"));
			}
		}

		return null;
	}

	public String getAsString(FacesContext facesContext, UIComponent component,
			Object value) {
		if (value == null || value.equals("")) {
			return "";
		} else {
			return String.valueOf(((Player) value).getNumber());
		}
	}
}
